import hashlib
import time

from django.contrib.auth.hashers import make_password, check_password
from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from App.models import Wheel, Nav, MustBuy, Shop, MainShow, FoodTypes, Goods, User, Cart, Order, OrderGoods
from App.utlis import sendEmail, get_color, generate_code, get_total_price, get_final_price


def test(request):
    print('你好')
    return HttpResponse('爱鲜蜂项目现在开启，良好的开端是成功的一半！！！')

def main(request):
    return render(request,'base_main.html')

# 主页
def home(request):

    wheels = Wheel.objects.all()
    navs = Nav.objects.all()
    mustbuys = MustBuy.objects.all()
    shop0_1 = Shop.objects.all()[0:1]
    shop1_3 = Shop.objects.all()[1:3]
    shop3_7 = Shop.objects.all()[3:7]
    shop7_11 = Shop.objects.all()[7:11]
    mainshows = MainShow.objects.all()

    print('123')
    data= {
        'Title':'首页',
        'wheels':wheels,
        'navs':navs,
        'mustbuys':mustbuys,
        'shop0_1':shop0_1,
        'shop1_3':shop1_3,
        'shop3_7':shop3_7,
        'shop7_11':shop7_11,
        'mainshows':mainshows,

    }
    return render(request,'main/home.html',context=data)

# 闪购
def market(request):

    # 左侧分类查询
    foodtypes = FoodTypes.objects.all()
    typeid = request.GET.get('typeid','104749')
    sortby = request.GET.get('sortby')


    childcid = request.GET.get('childcid','0')
    print(childcid)
    print(type(childcid))

    childnames = FoodTypes.objects.filter(typeid=typeid).first().childtypenames

    childname_list = childnames.split('#')
    ch_list = []
    for child_name in childname_list:
        ch_name_list  = child_name.split(':')
        ch_list.append(ch_name_list)
        print(ch_name_list[1])
    print('******************')
    print(typeid)
    print(childcid)
    sort_list = ['综合排序','销量最高','价格最低','价格最高']
    if not childcid or childcid == '0':
        if not sortby:
            goods = Goods.objects.filter(categoryid=typeid)
        elif sortby == '综合排序':
            goods = Goods.objects.filter(categoryid=typeid)
        elif sortby == '销量最高':
            goods = Goods.objects.filter(categoryid=typeid).order_by('-productnum')
        elif sortby == '价格最低':
            goods = Goods.objects.filter(categoryid=typeid).order_by('price')
        elif sortby == '价格最高':
            goods = Goods.objects.filter(categoryid=typeid).order_by('-price')
    else:
        if not sortby:
            goods = Goods.objects.filter(childcid=int(childcid))
        elif sortby == '综合排序':
            goods = Goods.objects.filter(childcid=int(childcid))
        elif sortby == '销量最高':
            goods = Goods.objects.filter(childcid=int(childcid)).order_by('-productnum')
        elif sortby == '价格最低':
            goods = Goods.objects.filter(childcid=int(childcid)).order_by('price')
        elif sortby == '价格最高':
            goods = Goods.objects.filter(childcid=int(childcid)).order_by('-price')
    # for good in goods:
    #     c_goods_num = Cart.objects.filter(c_goods=good).first().c_goods_num
    #     if not c_goods_num:
    #         c_goods_num = 0

    # carts = Cart.objects.filter(c_is_select=True)
    goods_list = goods.filter(cart__c_is_select=True)
    data = {
        'Title': '闪购',
        'foodtypes': foodtypes,
        'goods':goods,
        'typeid':typeid,
        'ch_list':ch_list,
        'childcid':childcid,
        'sortby':sortby,
        'sort_list':sort_list,
        # 'carts':carts,
        'goods_list':goods_list,

    }

    return render(request,'main/market.html',context=data)

# 购物车
def cart(request):
    user_id = request.session.get('user_id')
    print(user_id,'****user_id******')
    if user_id:
        carts = Cart.objects.filter(c_user_id=user_id)
        carts_list = carts.all()
        print(carts_list)
        data = {
            'Title':'购物车',
            'cart_list':carts_list,
            'total_price':get_total_price()
        }
        return render(request, 'main/cart.html', context=data)
    else:
        return redirect(reverse('app:login'))
def mine(request):
    user_id = request.session.get('user_id')
    user01 = User.objects.filter(id=user_id).first()
        # print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    if user01:
        # print(user01.icon.url, 'register url**********************')
        data = {
            'Title':'我的',
            'user01':user01,
            'icon':'/static/uploads/' + user01.icon.url
        }
        print(user01.icon.url,'*******icon***************')
        return render(request, 'main/mine.html',context=data)
    else:
        return render(request,'main/mine.html')



# 注册
def register(request):
    if request.method == 'GET':
        data = {
            'Title':'注册'
        }
        return render(request,'user/register.html',context=data)
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(password,'注册的密码********************')
        password = make_password(password)
        email = request.POST.get('email')
        icon = request.FILES.get('icon')
        ip = request.META.get('REMOTE_ADDR')
        print(ip,'***********ip***********')
        print(icon)
        user = User()
        user.username = username
        user.password = password
        user.email = email
        user.icon = icon
        u_token = generate_token(ip, user.username)
        user.u_token = u_token
        cache.set(u_token, u_token, timeout=300)
        sendEmail(username,email,u_token)
        user.save()
        request.session['u_token'] = u_token
        # print(request.session.get('utoken'), '******获utoken')
        # print('邮件呢？？？？？？？？？？？？？？？？？？？？？？？')
        return redirect(reverse('app:login'))


# 登录
def login(request):
    if request.method == 'GET':
        msg = request.session.get('error_message')
        data = {
            'title': '登录',
        }
        request.session.flush()
        if msg:
            data['msg']=msg
        return render(request,'user/login.html',context=data)
    if request.method == 'POST':
        imgcode = request.POST.get('imgcode').lower()
        print(imgcode,'****************imgcode****')
        code = request.session.get('verify_code').lower()
        print(code, '****************code****')
        if code == imgcode:
            print('一样的************')
            username = request.POST.get('username')
            password = request.POST.get('password')
            print('========================')
            print(password)
            user = User.objects.filter(username=username).first()
            data={
                'msg':'ok',
            }
            if user:
                if check_password(password,user.password):
                    request.session['user_id'] = user.id
                    return redirect(reverse('app:mine'))
                else:
                    # data['msg']='密码错误'
                    # return render(request,'user/login.html',context=data)
                    request.session['error_message']='密码错误'
                    return redirect(reverse('app:login'))
            else:
                # data['msg'] = '用户名字错误'
                # return render(request, 'user/login.html', context=data)
                request.session['error_message'] = '用户名不存在'
                return redirect(reverse('app:login'))
        else:
            request.session['error_message'] = '验证码错误'
            return redirect(reverse('app:login'))

# 注册验证
def checkregister(request):
    username = request.GET.get('username')
    user = User.objects.filter(username=username).first()
    data = {
        'msg':'用户名可用',
        'status':200
    }
    if user:
        data['msg']= '用户名已被占用'
        data['status'] = 202
    return JsonResponse(data)

# 登出
def logout(request):
    # user_id = request.session.get('user_id')
    request.session.flush()
    return redirect(reverse('app:mine'))


#生成token
def generate_token(ip,username):
    c_time = time.ctime()
    s = ip + username + c_time
    token = hashlib.new('md5',s.encode('utf-8')).hexdigest()
    return token

# 激活账户
def active(request):
    utoken = request.session.get('u_token')
    if utoken:
        u_token = request.GET.get('u_token')
        print(u_token,'********user_id**************')
        if cache.get(u_token):
            user = User.objects.filter(u_token=u_token).last()
            user.active = True
            user.save()
            request.session.flush()
            return  render(request,'user/active_success.html')
        return render(request,'user/active_failed.html')
    else:
        return HttpResponse('已经激活成功，不能再次激活')

# 生成验证码
def get_code(request):
    # 初始化画布，初始化画笔
    # mode = "RGB"
    # size = (200, 100)
    # red = get_color()
    # green = get_color()
    # blue = get_color()
    # color_bg = (red, green, blue)
    # image = Image.new(mode=mode, size=size, color=color_bg)
    # imagedraw = ImageDraw(image, mode=mode)
    # imagefont = ImageFont.truetype(settings.FONT_PATH, 40)
    # verify_code = generate_code()
    # print(verify_code, 'verify_code******************************')
    # request.session['verify_code'] = verify_code
    # for i in range(4):
    #     fill = (get_color(), get_color(), get_color())
    #     imagedraw.text(xy=(50 * i, 0), text=verify_code[i], font=imagefont, fill=fill)
    # for i in range(10):
    #     fill = (get_color(), get_color(), get_color())
    #     xy = (random.randrange(201), random.randrange(100))
    #     imagedraw.point(xy=xy, fill=fill)
    # fp = BytesIO()
    # image.save(fp, "png")
    # return HttpResponse(fp.getvalue(), content_type="image/png")

    # # 引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量，用于画面的背景色、宽度、高度
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), random.randrange(20, 100))
    width = 200
    height = 100
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 创建4位验证码
    str = '1234567890QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm'
    rand_str = ''
    for i in range(0, 4):
        rand_str += str[random.randrange(0, len(str))]
    # 构造字体对象
    font = ImageFont.truetype(r'C:\Windows\Fonts\Lobster-Regular.ttf', 40)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字样式
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    del draw
    # 存入session 用于进一步验证
    # request.session['verify']=rand_str
    # cache.set('verify', rand_str)
    request.session['verify_code'] = rand_str
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中 文件为PNG
    im.save(buf, 'png')
    # 返回给客户端 MIME类型为img/png
    return HttpResponse(buf.getvalue(), 'image/png')

# 增减商品
def add_cart(request):
    c_user_id = request.session.get('user_id')
    data = {
        'status': 200,

    }
    if c_user_id:
        c_goods_id = request.GET.get('goodsid')
        means = request.GET.get('means')
        carts = Cart.objects.filter(c_user_id=c_user_id).filter(c_goods_id=c_goods_id)

        if carts.exists():
            cart = carts.first()
            if means == 'add':
                cart.c_goods_num += 1
                cart.save()
                data['c_goods_num'] = cart.c_goods_num
            elif means == 'dec':
                cart.c_goods_num -= 1
                if cart.c_goods_num == 0:
                    cart.delete()
                else:
                    cart.save()
                data['c_goods_num'] = cart.c_goods_num
        else:
            if means == 'add':
                cart = Cart()
                cart.c_user_id = c_user_id
                cart.c_goods_id = c_goods_id
                cart.c_goods_num = 1
                cart.save()
                data['c_goods_num'] = cart.c_goods_num
            elif means == 'dec':
                data['status'] = 201
        data['total_price'] = get_total_price()
        return JsonResponse(data)
    else:
        return JsonResponse({'status': 204})

# 点击切换选中状态
def chselect(request):
    cartid = request.GET.get('cartid')
    user_id = request.session.get('user_id')
    cart = Cart.objects.get(pk=cartid)

    data = {
        'status':200,
        'msg':'被选中'
    }

    if cart.c_is_select == True:
        cart.c_is_select = not cart.c_is_select
        cart.save()
        data['status'] = 201
        data['msg'] = '未选中'

    else:
        cart.c_is_select = not cart.c_is_select
        cart.save()
    is_all_select = not Cart.objects.filter(c_user_id=user_id).filter(c_is_select=False).exists()
    data['is_all_select'] = is_all_select
    data['total_price'] = get_total_price()
    print(get_total_price(),'*******zongjia**********')
    return JsonResponse(data)

# 点击全选
def allselect(request):
    cart_list = request.GET.get('cart_list')
    cart_list = cart_list.split('#')
    carts = Cart.objects.filter(id__in=cart_list)
    for cart in carts:
        cart.c_is_select = not cart.c_is_select
        cart.save()
    data = {
        'status':200,
        'msg':'ok',
        'total_price':get_total_price()

    }
    return JsonResponse(data)


def orderdetail(request):
    print('******刚进函数里面************')
    user_id = request.session.get('user_id')
    carts = Cart.objects.filter(c_user_id=user_id).filter(c_is_select=True)
    order = Order()
    o_user = User.objects.get(pk=user_id)
    order.o_user = o_user
    order.o_price = get_total_price()
    # order.o_price = get_total_price()
    # total_price = order.o_price

    order.save()
    for cart_obj in carts:
        ordergoods = OrderGoods()
        ordergoods.o_order = order
        ordergoods.o_goods_num = cart_obj.c_goods_num
        ordergoods.o_goods = cart_obj.c_goods
        ordergoods.save()
        cart_obj.delete()

    order = Order.objects.get(pk=order.id)
    # ordergoods_list = OrderGoods.objects.all()
    data = {
        'title': '订单列表',
        'order': order,
        # 'ordergoods_list': ordergoods_list,
    }

    return render(request, 'order/order_detail.html', context=data)

    # # carts = Cart.objects.filter(c_user_id=user_id).filter(c_is_select=True)
    # # print(carts,'carts***************')
    # goods_list = Goods.objects.filter(cart__c_is_select=True)
    # print(goods_list)
    # type(goods_list)
    #
    # print(goods_list,'****-------*************************')
    # for goods in goods_list:
    #     # 选中的商品的数量
    #     goods_num = Cart.objects.filter(c_goods=goods).first().c_goods_num
    #     print(goods_num)
    #     # 把每一个选中的商品及其数量添加到订单商品表中
    #     ordergoods = OrderGoods()
    #     ordergoods.o_order = Order.objects.filter(o_user=o_user).first()
    #     ordergoods.o_goods = goods
    #     ordergoods.o_goods_num = goods_num
    #     ordergoods.save()
    # Cart.objects.all().delete()
    # ordergoods_list = OrderGoods.objects.all()
    # final_price = get_final_price()
    # data = {
    #     'Title':'订单详情',
    #     'final_price':final_price,
    #     'ordergoods_list':ordergoods_list,
    #     'order':order
    # }




